﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using iRemoteComputing.Phone.ServiceReference1;
using Microsoft.Phone.Shell;

namespace iRemoteComputing.Phone.Pages
{
    public partial class LoginPage : PhoneApplicationPage
    {
        private Service1Client client = new Service1Client();
        IDictionary<string, object> stateStore = PhoneApplicationService.Current.State;

        string password = "", username = "";

        public LoginPage()
        {
            if (stateStore.ContainsKey("loginUser") && stateStore.ContainsKey("loginPassword"))
            {
                this.password = (string)stateStore["loginPassword"];
                this.username = (string)stateStore["loginUser"];
                client.LoginAsync(username, password);
                client.LoginCompleted += new EventHandler<ServiceReference1.LoginCompletedEventArgs>(client_loginCompleted);
            }

            InitializeComponent();
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            client.LoginAsync(UserNameTextBox.Text, PasswordBox.Password);
            client.LoginCompleted +=new EventHandler<ServiceReference1.LoginCompletedEventArgs>(client_loginCompleted);
        }

        private void client_loginCompleted(object sender, ServiceReference1.LoginCompletedEventArgs e)
        {
            if (e.Result)
            {
                StatusLabel.Text = "Success.";

                stateStore.Remove("loginPassword");
                stateStore.Add("loginPassword", this.password);
                stateStore.Remove("loginUser");
                stateStore.Add("loginUser", this.password);

                NavigationService.Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                StatusLabel.Text = "Invalid credentials. Please try again.";
            }
        }
    }
}